package cn.tsvtc.shop.controller;

import cn.tsvtc.shop.constant.RedisConstant;
import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.pojo.Order;
import cn.tsvtc.shop.service.PayService;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("pay")
@Slf4j
public class PayController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    PayService payService;


    private HttpServletRequest httpRequest;
    private HttpServletResponse httpResponse;

    /**
     * 支付接口
     * @param orderno
     * @param httpRequest
     * @param httpResponse
     * @throws ServletException
     * @throws IOException
     */
    @GetMapping("returnurl")
    public void doPost(
            String orderno,
            HttpServletRequest httpRequest,
            HttpServletResponse httpResponse) throws ServletException, IOException {
        this.httpRequest = httpRequest;
        this.httpResponse = httpResponse;

        //获取order对象
        Object o = redisTemplate.opsForValue().get(RedisConstant.ORDER + orderno);
        Order order= (Order) o;
        String form = "";
        form = payService.createForm(order);
        httpResponse.setContentType("text/html;charset=utf-8");
        httpResponse.getWriter().write(form); //直接将完整的表单html输出到页面
        httpResponse.getWriter().flush();
        httpResponse.getWriter().close();
    }


    /**
     * 支付成功后的回调，是由支付宝来调用的
     * @param model
     * @param total_amount
     * @return
     */
    @GetMapping("success")
    public String success(Model model, String total_amount,String out_trade_no){
        model.addAttribute("money",total_amount);
        model.addAttribute("out_trade_no",out_trade_no);
        return "success";
    }



    /**
     * 验签接口
     * @param request
     * @param response
     * @param orderno
     */
    @PostMapping("/notifyurl")
    public void notify(HttpServletRequest request, HttpServletResponse response, String orderno) {
        try {
            Map<String, String[]> parameterMap = request.getParameterMap();
            System.out.println(parameterMap);

            Map<String, String> paramsMap = new HashMap<>();

            for (String key : parameterMap.keySet()) {
                if(!"money".equalsIgnoreCase(key) && !"orderno".equalsIgnoreCase(key)) {
                    paramsMap.put(key, parameterMap.get(key)[0]);
                }

            }


            //验证
            Boolean validate = payService.validate(paramsMap, orderno);
            //存入redis

            log.error(" notify尝试存到redis===>"+RedisConstant.ORDER_VALI+orderno+validate);
            redisTemplate.opsForValue().set(RedisConstant.ORDER_VALI+orderno,validate);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("验签失败-> " + e.getMessage() );
        }

    }

    /**
     * 前端获取支付结果  jorpar6408@sandbox.com
     * @param orderno
     */
    @PostMapping("/getResult")
    @ResponseBody
    public ResultMessage getResult(String orderno) {
        try {
            log.error(" getResult尝试从redis获取===>"+RedisConstant.ORDER_VALI + orderno);
            Object o = redisTemplate.opsForValue().get(RedisConstant.ORDER_VALI + orderno);
            log.error(" getResult从redis获取orderno的值为===>"+o);
            Boolean bool= (Boolean) o;
            if(bool){
                return new ResultMessage(true,"success","支付宝返回成功");
            }else{
                return new ResultMessage(false,"failed","支付宝返回失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(false,"failed",e.getMessage());
        }
    }
}
